package tools

import (
	"os"
	"reflect"
	"slices"
	"testing"
)

func TestWithExit(t *testing.T) {
	mock := &ExitMock{}

	t.Run("ok", func(sub *testing.T) {
		expected := reflect.ValueOf(mock.exit).Pointer()
		WithExit(sub, mock)
		if result := reflect.ValueOf(mock.exit).Pointer(); result != expected {
			sub.Errorf("Exit() was expected to be replaced with %T.exit", mock)
		}
	})
}

func TestExitMock_LastCode(t *testing.T) {
	t.Run("ok", func(sub *testing.T) {
		mock := &ExitMock{}
		for i := 0; i < 10; i++ {
			mock.exit(i)
		}

		expected := 9
		if result := mock.LastCode(); result != expected {
			sub.Errorf("expected: %d, got: %d", expected, result)
		}
	})

	t.Run("did-not-exit", func(sub *testing.T) {
		if result := (&ExitMock{}).LastCode(); result != ExitOk {
			sub.Errorf("expected: %d, got: %d", ExitOk, result)
		}
	})
}

func TestWithArgs(t *testing.T) {
	set := []string{"this", "is", "the", "test"}
	origin := os.Args

	equal := slices.Equal[[]string]
	t.Run("sub", func(sub *testing.T) {
		WithArgs(sub, set)
		if !equal(os.Args, set) {
			sub.Errorf("WithArgs() arguments weren't set")
		}
	})
	if !equal(os.Args, origin) {
		t.Errorf("WithArgs() arguments weren't rollbacked")
	}
}
